package com.dckj.auto.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * @since 1.0
 * ${tags}
 * <br><b>作者： @author WangDong</b>
 * <br>创建时间：2018/2/13 0013 10:20
 */
public class PageUtils {

    /**
     * 得到当前页数 和 每页显示条数
     *
     * @since 1.0
     * @return <br>
     *         <b>作者： @author WangDong</b> <br>
     *         创建时间：2018-2-13 上午10:13:57
     */
    private static JSONObject getNumAndSize(HttpServletRequest request) {

        int pageNumber = 0;
        int pageSize = 0;
        JSONObject json = new JSONObject();
        String getPageNumber = request.getParameter("pageNumber");
        String getPageSize = request.getParameter("pageSize");
        if (StringUtils.isNotEmpty(getPageNumber) && StringUtils.isNotEmpty(getPageSize)) {

            pageNumber = Integer.valueOf(getPageNumber);
            pageSize = Integer.valueOf(getPageSize);
        } else {
            pageNumber = 1;
            pageSize = 20;
        }
        json.put("pageNumber", pageNumber);
        json.put("pageSize", pageSize);
        return json;
    }

    /**
     * 获取page
     * @param request
     * @return Page
     */
    public static Page getPage(HttpServletRequest request){
        JSONObject numAndSize = getNumAndSize(request);
        Integer pageCurrent = (Integer) numAndSize.get("pageNumber");
        Integer pageSize = (Integer) numAndSize.get("pageSize");
        return new Page<>(pageCurrent,pageSize);
    }

    /**
     * 获取current和size
     * @param request
     * @return
     */
    public static HashMap getPageCurrentAndSize(HttpServletRequest request){
        JSONObject numAndSize = getNumAndSize(request);
        HashMap map =new HashMap();
        map.put("pageCurrent",(Integer) numAndSize.get("pageNumber"));
        map.put("pageSize",(Integer) numAndSize.get("pageSize"));
        map.put("pageNumber",((Integer) numAndSize.get("pageNumber")-1)*((Integer) numAndSize.get("pageSize")));
        return map;
    }


    /**
     * 返回sql 分页所需的参数
     * @param request
     * @return
     */
    public static HashMap getServicePage(HttpServletRequest request){
        JSONObject numAndSize = getNumAndSize(request);
        Integer pageCurrent = (Integer) numAndSize.get("pageNumber");
        Integer pageSize = (Integer) numAndSize.get("pageSize");
        HashMap<String,Integer> map=new HashMap<>();
        map.put("pageNumber",pageCurrent);
        map.put("pageCurrent",(pageCurrent-1)*pageSize);
        map.put("pageSize",pageSize);
        return map;
    }

}
